package club.itstudio.IContainer.controller.common;

import club.itstudio.IContainer.annotation.LoginRequired;
import club.itstudio.IContainer.entity.User;
import club.itstudio.IContainer.exception.BaseException;
import club.itstudio.IContainer.exception.ParamInvalidException;
import club.itstudio.IContainer.service.AuthService;
import club.itstudio.IContainer.service.UserService;
import club.itstudio.IContainer.util.Hash;
import club.itstudio.IContainer.util.Result;
import club.itstudio.IContainer.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/change_password")
public class ChangePasswordController {

    AuthService authService;
    UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setAuthService(AuthService authService) {
        this.authService = authService;
    }

    @LoginRequired
    @PostMapping
    public Result changePassword(@RequestParam String oldPassword,
                                 @RequestParam String newPassword) {
        User user = authService.threadLocalUsers.get();
        if (!user.password.equals(Hash.SHA256(oldPassword))) {
            throw new BaseException("当前密码错误");
        }

        if (newPassword.length() < 6 || newPassword.length() > 30) throw new ParamInvalidException("密码长度为6-30位");

        user.password = Hash.SHA256(newPassword);
        userService.updatePassword(user);

        return ResultUtil.success();
    }
}
